package com.hzw.saas.service.old.hub.util;

import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class S3FileStreamUtils {

    static int BUF_SIZE = 8192;

    public static void pipeStream(InputStream ins, OutputStream ous) throws IOException {
        ExecutorService executor = new ThreadPoolExecutor(1, 3,
            60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());
        // read ins write to pous
        final PipedOutputStream pous = new PipedOutputStream();
        executor.submit(() -> {
            try {
                FileStreams.readAndWrite(ins, pous, BUF_SIZE, true);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        // read pins write to ous
        final PipedInputStream pins = new PipedInputStream(pous, BUF_SIZE);
        try {
            FileStreams.readAndWrite(pins, ous, BUF_SIZE, false);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                pous.close();
                pins.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
